今天提供幾個針對程式碼風格的人工 Code Review 實作範例,也是Prettier 和 ESLint 比較難檢查到的。
原始程式碼:
function fetchData(userId) {
  let user = getUser(userId);
  if (user) {
    if (user.isActive == true) {
      doSomethingWithUser(user);
    } else {
      logError('User is inactive');
    }
  } else {
    logError('User not found');
  }
}
調整後程式碼:
// 宣告error messages 的字串為變數
const ERROR_MESSAGES = {
  userNotFound: 'User not found',
  userInactive: 'User is inactive'
};
// 取更能描述該功能的名字
function processUser(userId) {
  const user = getUser(userId);
  
// if...else 簡化為一層
  if (!user) {
    logError(ERROR_MESSAGES.userNotFound);
    return;
  }
  
// 簡化條件判斷
  if (!user.isActive) {
    logError(ERROR_MESSAGES.userInactive);
    return;
  }
  doSomethingWithUser(user);
}
原始程式碼:
function calculate_sum( a, b ) {
    if ( a === null || b === null ) {
        return
    }
    return a + b
}
const temp = calculate_sum( 2, 3 );
let person = { Name: 'John', age: 25 };
調整後程式碼:
function calculateSum(a, b) {
    if (a === null || b === null) {
        return undefined;
    }
    return a + b;
}
const sum = calculateSum(2, 3);
let person = {
    name: 'John',
    age: 25
};
今天提供兩個範例,給 Code Reviewer 在針對程式碼風格檢查時,可以有依循的方向。